﻿using Microsoft.Extensions.DependencyInjection;
using System;
using NetMicro.Core.ConfigureOptions;
using NetMicro.Core.Helper;
using NetMicro.Core.Ioc.Attributes;
using NetMicro.Swagger.Builders;
using NetMicro.Swagger.Extensions.Options;
using NetMicro.Swagger.Options;

namespace NetMicro.Swagger.Extensions
{
    /// <summary>
    /// Swagger服务拓展类
    /// </summary>
    [SkipScan]
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Swagger服务
        /// </summary>
        /// <param name="mvcBuilder">Mvc 构建器</param>
        /// <param name="configure">自定义配置</param>
        /// <returns>服务集合</returns>
        public static IMvcBuilder AddSwaggers(this IMvcBuilder mvcBuilder, Action<SwaggerServiceOptions> configure = default)
        {
            mvcBuilder.Services.AddSwaggers(configure);

            return mvcBuilder;
        }

        /// <summary>
        /// 添加Swagger服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configure">自定义配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSwaggers(this IServiceCollection services, Action<SwaggerServiceOptions> configure = default)
        {
            SwaggerSettingsOptions settings = App.GetConfig<SwaggerSettingsOptions>("SwaggerSettings", true);
            // 判断是否启用Swagger
            if (settings.EnableSwagger != true) return services;

            // 添加配置
            services.AddConfigure<SwaggerSettingsOptions>();

            // 载入服务配置选项
            SwaggerServiceOptions configureOptions = new SwaggerServiceOptions();
            configure?.Invoke(configureOptions);

            // 添加Swagger生成器服务
            services.AddSwaggerGen(options => SwaggerBuilder.BuildGen(options, configureOptions?.SwaggerGenConfigure));

            // 添加 MiniProfiler 服务
            AddMiniProfiler(services, settings);

            return services;
        }

        /// <summary>
        /// 添加 MiniProfiler 配置
        /// </summary>
        /// <param name="services"></param>
        private static void AddMiniProfiler(IServiceCollection services, SwaggerSettingsOptions settings)
        {
            // 注册MiniProfiler 组件
            if (settings.EnableMiniProfiler != true) return;

            services.AddMiniProfiler(options =>
            {
                options.RouteBasePath = "/index-mini-profiler";
                options.EnableMvcFilterProfiling = false;
                options.EnableMvcViewProfiling = false;
            });
        }
    }
}